package com.hubujun.driverlicense.db;


import com.hubujun.driverlicense.DLExternalPath;
import com.hubujun.driverlicense.util.Ln;

import java.io.File;
import java.util.HashMap;

public class AccountStorage {

    public static final int DB_VERSION = 1;

    private String mResRoot;

    private SqliteDB mSqlDB;

    private HashMap<String, BuildTable> tables = new HashMap<String, BuildTable>();

    private QuestionStorage questionStorage;

    public AccountStorage(String resRoot) {
        mResRoot = resRoot;

        File path = new File(DLExternalPath.CORE_PATH);
        if (!path.exists()) {
            path.mkdirs();
        }

        BuildTable t = new QuestionStorage.QuestionStorageBuildTable();
        tables.put(t.getName(), t);
    }

    /**
     * 数据库文件是否已创建
     *
     * @return
     */
    public boolean isDatabaseCreated() {
        File dbFile = new File(DLExternalPath.getMainDatabasePath());
        if (dbFile.exists()) {
            Ln.d("ykss dbFile has create");
            return true;
        } else {
            Ln.d("ykss dbFile not create");
            return false;
        }
    }

    public void init() {
        String dbFile = DLExternalPath.getMainDatabasePath();

        File path = new File(DLExternalPath.CORE_PATH);
        if (!path.exists()) {
            path.mkdirs();
        }
        path = new File(mResRoot);
        if (!path.exists()) {
            path.mkdirs();
        }

        close();
        mSqlDB = new SqliteDB();
        if (!mSqlDB.openDatebase(dbFile, null, DB_VERSION, tables))
            throw new RuntimeException("mSqlDB.openDatebase fail");
        // TODO 初始化接口
        questionStorage = new QuestionStorage(mSqlDB);
    }

    public SqliteDB getSQLDB() {
        return mSqlDB;
    }

    public QuestionStorage getQuestionStorage() {
        return questionStorage;
    }

    public void close() {
        if (mSqlDB != null) {
            mSqlDB.close();
            mSqlDB = null;
        }
    }

    public void setResRoot(String root) {
        if (!root.equalsIgnoreCase(mResRoot)) {
            mResRoot = root;
        }
    }

    public void release() {
        close();
    }

}
